/*
 * @description:
 * @author: <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @Date: 2024-02-09 14:59:09
 * @FilePath: \dynamic-conf\logger\logger.go
 * @LastEditTime: 2024-03-09 06:51:15
 * @LastEditors: <a href="mailto:joshualwork@163.com">joshua_liu</a>
 */
package logger

import (
	"fmt"
	"os"
	"strings"
	"time"

	log "github.com/sirupsen/logrus"
)

type LoggerFormatter struct {
}

func (c *LoggerFormatter) Format(entry *log.Entry) ([]byte, error) {
	dateTime := "2006-01-02 15:04:05.000"
	// timestamp := time.Now().Format(time.RFC3339)
	timestamp := time.Now().Format(dateTime)
	hostname, _ := os.Hostname()
	caller := entry.Caller
	f := caller.Function
	callline := caller.Line
	return []byte(fmt.Sprintf("[%s][%d] %s %s %s[%d]: %s\n", strings.ToUpper(entry.Level.String()),
		os.Getpid(), timestamp, hostname, f, callline, entry.Message)), nil
}

// tag represents the application name generating the log message. The tag
// string will appear in all log entires.
var tag string

func init() {
	tag = os.Args[0]
	log.SetReportCaller(true)
	log.SetFormatter(&LoggerFormatter{})
	log.Info(fmt.Sprintf("Logger %s format initialized.", tag))
}

// SetTag sets the tag.
func SetTag(t string) {
	tag = t
}

// SetLevel sets the log level. Valid levels are panic, fatal, error, warn, info and debug.
func SetLevel(level string) {
	lvl, err := log.ParseLevel(level)
	if err != nil {
		Fatal(fmt.Sprintf(`not a valid level: "%s"`, level))
	}
	log.SetLevel(lvl)
}

// Debug logs a message with severity DEBUG.
func Debug(format string, v ...interface{}) {
	log.Debug(fmt.Sprintf(format, v...))
}

// Error logs a message with severity ERROR.
func Error(format string, v ...interface{}) {
	log.Error(fmt.Sprintf(format, v...))
}

// Fatal logs a message with severity ERROR followed by a call to os.Exit().
func Fatal(format string, v ...interface{}) {
	log.Fatal(fmt.Sprintf(format, v...))
}

// Info logs a message with severity INFO.
func Info(format string, v ...interface{}) {
	log.Info(fmt.Sprintf(format, v...))
}

// Warning logs a message with severity WARNING.
func Warning(format string, v ...interface{}) {
	log.Warning(fmt.Sprintf(format, v...))
}
